#!/bin/bash

BACKUP_DIR=snap-configs

function i() {
	mkdir $BACKUP_DIR
	echo "$1" >$BACKUP_DIR/config
	echo $BACKUP_DIR >$BACKUP_DIR/ex.list
}

function b() {
	prefix=$1
	while [[ -d "$prefix" && ! -d "$prefix/$BACKUP_DIR" ]]; do
		prefix=../$prefix
	done
	if [[ ! -d "$prefix" ]]; then
		echo This path is not under a backup configuration yet.
		return 1
	fi

	flags=""
	if [[ -f "$prefix/$BACKUP_DIR/ex.list" ]]; then
		flags="$flags --exclude-from=$prefix/$BACKUP_DIR/ex.list"
	fi
	if [[ -f "$prefix/$BACKUP_DIR/in.list" ]]; then
		flags=--include-from="$prefix/$BACKUP_DIR/in.list $flags"
	fi
	if [[ -f "$prefix/$BACKUP_DIR/f.list" ]]; then
		flags="$flags --files-from=$prefix/$BACKUP_DIR/f.list"
	fi

	backup_path=$(<"$prefix/$BACKUP_DIR/config")
	if [[ "$backup_path" == ssh:* ]]; then
		full_backup_path="${backup_path#ssh:}/snap"
	elif [[ "$backup_path" == /* ]]; then
		full_backup_path="$backup_path/snap"
		mkdir -p "$full_backup_path"
	else
		full_backup_path="$prefix/$backup_path/snap"
		mkdir -p "$full_backup_path"
	fi
	#incr_backup_path="../incr/$(date +"%Y-%m-%d.%H.%M").$2"
	new_snap="snap.$(date +"%Y-%m-%d.%H.%M").$2"
	
	rsync -aruvth --delete --progress --ignore-existing --link-dest="../last/" $flags "$prefix/" "$full_backup_path/$new_snap/"
	ln -sf "$new_snap" "$full_backup_path/last"
}

function h() {
	cat <<"eof"
子命令：
  * init path - 初始化仓库并指定备份路径，远程路径需加前缀"ssh:"
  * backup comment - 备份一次
  * help - 打印本帮助
特殊文件：
  特殊文件均在backup-configs文件夹下
  * config - 路径配置文件
  * ex.list - 用于rsync的--exclude-from选项
  * in.list - 用于rsync的--include-from选项
  * f.list - 用于rsync的--files-from选项
附录：
  rsync选项：-aruvth --delete --progress --ignore-existing
eof
}

case $1 in
	init)
		echo "${2:?Empty Backup Path!}"
		i "$2";;
	backup)
		#b ${2:-.};;
		b . "${2:-default}";;
	help)
		h;;
esac
